﻿using AyuBookmark.Common.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.Controls
{
    /// <summary>
    /// 分类树形控件（支持多级分类展示）
    /// </summary>
    public class CategoryTree : TreeView
    {
        private const int DefaultNodeHeight = 28;
        private Color _categoryColor = Color.FromArgb(240, 240, 240);
        private Color _selectedColor = Color.FromArgb(220, 235, 252);
        private Color _hoverColor = Color.FromArgb(230, 240, 250);
        private TreeNode _hoveredNode;

        public CategoryTree()
        {
            // 基础设置
            SetStyle(ControlStyles.OptimizedDoubleBuffer |
                   ControlStyles.AllPaintingInWmPaint |
                   ControlStyles.ResizeRedraw, true);
            DrawMode = TreeViewDrawMode.OwnerDrawAll;
            ShowLines = false;
            ShowPlusMinus = false;
            ShowRootLines = false;
            ItemHeight = DefaultNodeHeight;
            BorderStyle = BorderStyle.None;
            HideSelection = false;

            // 事件绑定
            DrawNode += OnDrawNode;
            MouseMove += OnMouseMove;
            MouseLeave += OnMouseLeave;
        }

        #region 属性
        /// <summary>
        /// 分类节点高度
        /// </summary>
        [DefaultValue(DefaultNodeHeight)]
        public new int ItemHeight
        {
            get => base.ItemHeight;
            set => base.ItemHeight = value;
        }

        /// <summary>
        /// 分类节点背景色
        /// </summary>
        [DefaultValue(typeof(Color), "240, 240, 240")]
        public Color CategoryColor
        {
            get => _categoryColor;
            set
            {
                _categoryColor = value;
                Invalidate();
            }
        }

        /// <summary>
        /// 选中节点颜色
        /// </summary>
        [DefaultValue(typeof(Color), "220, 235, 252")]
        public Color SelectedColor
        {
            get => _selectedColor;
            set
            {
                _selectedColor = value;
                Invalidate();
            }
        }

        /// <summary>
        /// 鼠标悬停颜色
        /// </summary>
        [DefaultValue(typeof(Color), "230, 240, 250")]
        public Color HoverColor
        {
            get => _hoverColor;
            set
            {
                _hoverColor = value;
                Invalidate();
            }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 加载分类数据
        /// </summary>
        public void LoadCategories(IEnumerable<Category> categories)
        {
            BeginUpdate();
            Nodes.Clear();

            // 构建分类树
            var rootNodes = new Dictionary<int, TreeNode>();
            foreach (var category in categories)
            {
                var node = new TreeNode(category.Name)
                {
                    Tag = category,
                    ForeColor = ColorTranslator.FromHtml(category.Color),
                    NodeFont = new Font(Font, FontStyle.Bold)
                };

                if (category.ParentId == null)
                {
                    Nodes.Add(node);
                }
                else if (rootNodes.ContainsKey(category.ParentId.Value))
                {
                    rootNodes[category.ParentId.Value].Nodes.Add(node);
                }

                rootNodes[category.Id] = node;
            }

            ExpandAll();
            EndUpdate();
        }

        /// <summary>
        /// 获取当前选中的分类
        /// </summary>
        public Category GetSelectedCategory()
        {
            return SelectedNode?.Tag as Category;
        }
        #endregion

        #region 事件处理
        private void OnDrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            if (e.Node == null) return;

            // 计算绘制区域
            var bounds = e.Bounds;
            bounds.Width = ClientSize.Width;

            // 背景色
            Color backColor;
            if (e.Node.IsSelected)
            {
                backColor = SelectedColor;
            }
            else if (e.Node == _hoveredNode)
            {
                backColor = HoverColor;
            }
            else
            {
                backColor = CategoryColor;
            }

            // 绘制背景
            using (var brush = new SolidBrush(backColor))
            {
                e.Graphics.FillRectangle(brush, bounds);
            }

            // 绘制图标和文本
            int offset = e.Node.Level * 20 + 8;
            var textRect = new Rectangle(
                bounds.X + offset,
                bounds.Y,
                bounds.Width - offset,
                bounds.Height);

            TextRenderer.DrawText(
                e.Graphics,
                e.Node.Text,
                e.Node.NodeFont ?? Font,
                textRect,
                e.Node.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            // 绘制展开/折叠图标
            if (e.Node.Nodes.Count > 0)
            {
                var iconRect = new Rectangle(
                    bounds.X + e.Node.Level * 20 + 4,
                    bounds.Y + (bounds.Height - 16) / 2,
                    16, 16);

                var iconChar = e.Node.IsExpanded ? '▼' : '▶';
                TextRenderer.DrawText(
                    e.Graphics,
                    iconChar.ToString(),
                    Font,
                    iconRect,
                    Color.Gray,
                    TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
            }
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            var node = GetNodeAt(e.Location);
            if (node != null)
            {
                Cursor = Cursors.Hand;
                if (_hoveredNode != node)
                {
                    _hoveredNode = node;
                    Invalidate();
                }
            }
            else
            {
                Cursor = Cursors.Default;
                if (_hoveredNode != null)
                {
                    _hoveredNode = null;
                    Invalidate();
                }
            }
        }

        private void OnMouseLeave(object sender, EventArgs e)
        {
            if (_hoveredNode != null)
            {
                _hoveredNode = null;
                Invalidate();
            }
            Cursor = Cursors.Default;
        }
        #endregion

        #region 辅助方法
        protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)
        {
            base.OnNodeMouseClick(e);

            // 点击展开/折叠图标区域
            if (e.Node.Nodes.Count > 0 &&
                e.X < e.Node.Bounds.Left + e.Node.Level * 20 + 20)
            {
                e.Node.Toggle();
            }
        }

        protected override void OnAfterSelect(TreeViewEventArgs e)
        {
            base.OnAfterSelect(e);
            OnCategorySelected?.Invoke(this, new CategoryEventArgs(e.Node.Tag as Category));
        }
        #endregion

        #region 自定义事件
        public event EventHandler<CategoryEventArgs> OnCategorySelected;

        public class CategoryEventArgs : EventArgs
        {
            public Category Category { get; }

            public CategoryEventArgs(Category category)
            {
                Category = category;
            }
        }
        #endregion
    }
}